package com.hafiery.sdk.bluetooth.transport.req;

import java.util.Arrays;

import static com.hafiery.sdk.bluetooth.transport.constant.OpCode.HEAD;
import static com.hafiery.sdk.bluetooth.transport.constant.OpCode.FLAG;
import static com.hafiery.sdk.bluetooth.transport.constant.OpCode.RESERVED;
import static com.hafiery.sdk.bluetooth.transport.constant.OpCode.TAIL;

public class RequestData {
    private final int opCode;
    private final int dataLength;
    private byte[] data;
    private RequestData(int code, byte[] payload) {
        this.opCode = code;
        this.dataLength = payload == null? 0 : payload.length;
        if (dataLength > 0) {
            this.data = Arrays.copyOf(payload, dataLength);
        }
    }

    public int getOpCode() {
        return opCode;
    }

    public byte[] getByteData() {
        byte[] result = new byte[HEAD.length+2+FLAG.length+RESERVED.length+1+dataLength+TAIL.length];
        System.arraycopy(HEAD, 0, result, 0, HEAD.length);
        result[HEAD.length] = (byte) (0x00ff & opCode);
        result[HEAD.length+1] = (byte) (0x00ff & (opCode >> 8));
        System.arraycopy(FLAG, 0, result, HEAD.length+2, FLAG.length);
        System.arraycopy(RESERVED, 0, result, HEAD.length+3, RESERVED.length);
        result[HEAD.length+4] = (byte) dataLength;
        if (dataLength > 0) {
            System.arraycopy(data, 0, result, HEAD.length+5, dataLength);
        }
        System.arraycopy(TAIL, 0, result, result.length-2, TAIL.length);
        return result;
    }

    public static class Builder{
        private int opCode;
        private byte[] payload;

        public Builder cmd(int opCode) {
            this.opCode = opCode;
            return this;
        }
        public Builder payload(byte[] payload) {
            this.payload = payload;
            return this;
        }
        public RequestData build() {
            return new RequestData(opCode,payload);
        }
    }

}
